<?php
/**
 * 数据库表结构和日志系统
 * Database Schema and Logging System
 * 
 * @package WP Bootstrap Woo
 */

if (!defined('ABSPATH')) {
    exit;
}

/**
 * 数据库管理器类
 */
class WBW_Database_Manager {
    
    private $table_prefix;
    
    public function __construct() {
        global $wpdb;
        $this->table_prefix = $wpdb->prefix . 'wbw_';
    }
    
    /**
     * 创建数据库表
     */
    public function create_tables() {
        $this->create_syntax_check_logs_table();
        $this->create_syntax_check_config_table();
        $this->create_backup_logs_table();
    }
    
    /**
     * 创建语法检查日志表
     */
    private function create_syntax_check_logs_table() {
        global $wpdb;
        
        $table_name = $this->table_prefix . 'syntax_check_logs';
        
        $charset_collate = $wpdb->get_charset_collate();
        
        $sql = "CREATE TABLE $table_name (
            id bigint(20) NOT NULL AUTO_INCREMENT,
            check_time datetime NOT NULL,
            file_path varchar(500) NOT NULL,
            file_type varchar(50) NOT NULL,
            check_category enum('syntax','performance','security') NOT NULL DEFAULT 'syntax',
            status enum('success','error','warning') NOT NULL,
            error_message text,
            error_line int(11),
            auto_fixed tinyint(1) DEFAULT 0,
            performance_score int(3),
            optimization_suggestions json,
            created_at timestamp DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY (id),
            INDEX idx_check_time (check_time),
            INDEX idx_file_path (file_path),
            INDEX idx_status (status),
            INDEX idx_category (check_category)
        ) $charset_collate;";
        
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        dbDelta($sql);
    }
    
    /**
     * 创建配置表
     */
    private function create_syntax_check_config_table() {
        global $wpdb;
        
        $table_name = $this->table_prefix . 'syntax_check_config';
        
        $charset_collate = $wpdb->get_charset_collate();
        
        $sql = "CREATE TABLE $table_name (
            id int(11) NOT NULL AUTO_INCREMENT,
            config_key varchar(100) NOT NULL,
            config_value longtext,
            description text,
            updated_at timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            PRIMARY KEY (id),
            UNIQUE KEY config_key (config_key)
        ) $charset_collate;";
        
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        dbDelta($sql);
        
        // 插入默认配置
        $this->insert_default_config();
    }
    
    /**
     * 创建备份日志表
     */
    private function create_backup_logs_table() {
        global $wpdb;
        
        $table_name = $this->table_prefix . 'backup_logs';
        
        $charset_collate = $wpdb->get_charset_collate();
        
        $sql = "CREATE TABLE $table_name (
            id bigint(20) NOT NULL AUTO_INCREMENT,
            backup_id varchar(50) NOT NULL,
            original_file varchar(500) NOT NULL,
            backup_file varchar(500) NOT NULL,
            file_size bigint(20),
            file_hash varchar(32),
            backup_type enum('auto','manual') DEFAULT 'auto',
            created_at timestamp DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY (id),
            INDEX idx_backup_id (backup_id),
            INDEX idx_original_file (original_file),
            INDEX idx_created_at (created_at)
        ) $charset_collate;";
        
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        dbDelta($sql);
    }
    
    /**
     * 插入默认配置
     */
    private function insert_default_config() {
        global $wpdb;
        
        $table_name = $this->table_prefix . 'syntax_check_config';
        
        $default_configs = array(
            array(
                'config_key' => 'auto_check_enabled',
                'config_value' => '1',
                'description' => '是否启用自动语法检查'
            ),
            array(
                'config_key' => 'auto_fix_enabled',
                'config_value' => '0',
                'description' => '是否启用自动修复'
            ),
            array(
                'config_key' => 'backup_retention_days',
                'config_value' => '30',
                'description' => '备份文件保留天数'
            ),
            array(
                'config_key' => 'performance_check_interval',
                'config_value' => '24',
                'description' => '性能检查间隔（小时）'
            )
        );
        
        foreach ($default_configs as $config) {
            $wpdb->replace($table_name, $config);
        }
    }
    
    /**
     * 记录语法检查日志
     */
    public function log_syntax_check($data) {
        global $wpdb;
        
        $table_name = $this->table_prefix . 'syntax_check_logs';
        
        $log_data = array(
            'check_time' => current_time('mysql'),
            'file_path' => $data['file_path'] ?? '',
            'file_type' => $data['file_type'] ?? 'unknown',
            'check_category' => $data['check_category'] ?? 'syntax',
            'status' => $data['status'] ?? 'success',
            'error_message' => $data['error_message'] ?? null,
            'error_line' => $data['error_line'] ?? null,
            'auto_fixed' => $data['auto_fixed'] ?? 0,
            'performance_score' => $data['performance_score'] ?? null,
            'optimization_suggestions' => isset($data['optimization_suggestions']) ? json_encode($data['optimization_suggestions']) : null
        );
        
        return $wpdb->insert($table_name, $log_data);
    }
    
    /**
     * 记录备份日志
     */
    public function log_backup($data) {
        global $wpdb;
        
        $table_name = $this->table_prefix . 'backup_logs';
        
        $backup_data = array(
            'backup_id' => $data['backup_id'] ?? '',
            'original_file' => $data['original_file'] ?? '',
            'backup_file' => $data['backup_file'] ?? '',
            'file_size' => $data['file_size'] ?? 0,
            'file_hash' => $data['file_hash'] ?? '',
            'backup_type' => $data['backup_type'] ?? 'auto'
        );
        
        return $wpdb->insert($table_name, $backup_data);
    }
    
    /**
     * 获取检查历史
     */
    public function get_check_history($limit = 50, $offset = 0) {
        global $wpdb;
        
        $table_name = $this->table_prefix . 'syntax_check_logs';
        
        $sql = $wpdb->prepare(
            "SELECT * FROM $table_name ORDER BY check_time DESC LIMIT %d OFFSET %d",
            $limit,
            $offset
        );
        
        return $wpdb->get_results($sql, ARRAY_A);
    }
    
    /**
     * 获取统计数据
     */
    public function get_statistics($days = 30) {
        global $wpdb;
        
        $table_name = $this->table_prefix . 'syntax_check_logs';
        $date_limit = date('Y-m-d H:i:s', strtotime("-{$days} days"));
        
        $stats = array();
        
        // 总检查次数
        $stats['total_checks'] = $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM $table_name WHERE check_time >= %s",
            $date_limit
        ));
        
        // 错误数量
        $stats['total_errors'] = $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM $table_name WHERE status = 'error' AND check_time >= %s",
            $date_limit
        ));
        
        // 警告数量
        $stats['total_warnings'] = $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM $table_name WHERE status = 'warning' AND check_time >= %s",
            $date_limit
        ));
        
        // 自动修复次数
        $stats['auto_fixes'] = $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM $table_name WHERE auto_fixed = 1 AND check_time >= %s",
            $date_limit
        ));
        
        // 平均性能评分
        $stats['avg_performance_score'] = $wpdb->get_var($wpdb->prepare(
            "SELECT AVG(performance_score) FROM $table_name WHERE performance_score IS NOT NULL AND check_time >= %s",
            $date_limit
        ));
        
        return $stats;
    }
    
    /**
     * 清理旧日志
     */
    public function cleanup_old_logs($days = 90) {
        global $wpdb;
        
        $table_name = $this->table_prefix . 'syntax_check_logs';
        $date_limit = date('Y-m-d H:i:s', strtotime("-{$days} days"));
        
        return $wpdb->query($wpdb->prepare(
            "DELETE FROM $table_name WHERE check_time < %s",
            $date_limit
        ));
    }
    
    /**
     * 获取配置值
     */
    public function get_config($key, $default = null) {
        global $wpdb;
        
        $table_name = $this->table_prefix . 'syntax_check_config';
        
        $value = $wpdb->get_var($wpdb->prepare(
            "SELECT config_value FROM $table_name WHERE config_key = %s",
            $key
        ));
        
        return $value !== null ? $value : $default;
    }
    
    /**
     * 设置配置值
     */
    public function set_config($key, $value, $description = '') {
        global $wpdb;
        
        $table_name = $this->table_prefix . 'syntax_check_config';
        
        return $wpdb->replace($table_name, array(
            'config_key' => $key,
            'config_value' => $value,
            'description' => $description
        ));
    }
    
    /**
     * 删除表
     */
    public function drop_tables() {
        global $wpdb;
        
        $tables = array(
            $this->table_prefix . 'syntax_check_logs',
            $this->table_prefix . 'syntax_check_config',
            $this->table_prefix . 'backup_logs'
        );
        
        foreach ($tables as $table) {
            $wpdb->query("DROP TABLE IF EXISTS $table");
        }
    }
}

/**
 * 日志记录器类
 */
class WBW_Logger {
    
    private $db_manager;
    private $log_file;
    
    public function __construct() {
        $this->db_manager = new WBW_Database_Manager();
        
        $upload_dir = wp_upload_dir();
        $this->log_file = $upload_dir['basedir'] . '/wbw-syntax-checker.log';
    }
    
    /**
     * 记录信息
     */
    public function info($message, $context = array()) {
        $this->log('INFO', $message, $context);
    }
    
    /**
     * 记录警告
     */
    public function warning($message, $context = array()) {
        $this->log('WARNING', $message, $context);
    }
    
    /**
     * 记录错误
     */
    public function error($message, $context = array()) {
        $this->log('ERROR', $message, $context);
    }
    
    /**
     * 记录调试信息
     */
    public function debug($message, $context = array()) {
        if (defined('WP_DEBUG') && WP_DEBUG) {
            $this->log('DEBUG', $message, $context);
        }
    }
    
    /**
     * 通用日志记录方法
     */
    private function log($level, $message, $context = array()) {
        $timestamp = current_time('Y-m-d H:i:s');
        $log_entry = "[{$timestamp}] [{$level}] {$message}";
        
        if (!empty($context)) {
            $log_entry .= ' ' . json_encode($context);
        }
        
        $log_entry .= "\n";
        
        // 写入文件
        file_put_contents($this->log_file, $log_entry, FILE_APPEND | LOCK_EX);
        
        // 写入数据库（仅对重要事件）
        if (in_array($level, array('ERROR', 'WARNING')) && isset($context['file_path'])) {
            $this->db_manager->log_syntax_check(array(
                'file_path' => $context['file_path'],
                'status' => strtolower($level) === 'error' ? 'error' : 'warning',
                'error_message' => $message,
                'check_category' => $context['category'] ?? 'syntax'
            ));
        }
    }
    
    /**
     * 清理旧日志文件
     */
    public function cleanup_log_file($max_size = 10485760) { // 10MB
        if (file_exists($this->log_file) && filesize($this->log_file) > $max_size) {
            $backup_file = $this->log_file . '.backup';
            rename($this->log_file, $backup_file);
            touch($this->log_file);
        }
    }
}